package main_com.filter;


import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取当前请求的路径
        String requestURI = request.getRequestURI();
        //创建不需要登录的字符串数组
        String[] urls = {
                "/main",
                "/login.jsp",
                "/index.jsp",
                "/LoginController/*",
                "/RegisterController/*",
                "/register/*",

        };
        //调用比对方法进行对比
        boolean b = checkUrl(urls, requestURI);
        //如果为true，则放行
        if (b) {
            //检测到用户不需要登录
            filterChain.doFilter(request, response);
            return;
        }
        //如果false则需要判断session是否为空，不为空则放行
        if (request.getSession().getAttribute("login") != null) {
            //检测到用户已经登录,放行
            filterChain.doFilter(request, response);
            return;
        }
        response.sendRedirect(request.getContextPath() + "/main");
    }

    public boolean checkUrl(String[] urls, String uri) {
        for (String url :
                urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
